package com.learn.http;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

public class httpclientTest2 {

	// @Test
	public void test() throws Exception {
		// CloseableHttpClient httpclient = HttpClients.createDefault();
		// HttpClientContext context = HttpClientContext.create();
		// HttpPost httpget = new HttpPost("http://pdf.starpost.cn");
		// CloseableHttpResponse response = httpclient.execute(httpget,
		// context);
		// try {
		// HttpHost target = context.getTargetHost();
		// List<URI> redirectLocations = context.getRedirectLocations();
		// URI location = URIUtils.resolve(httpget.getURI(), target,
		// redirectLocations);
		// System.out.println("Final HTTP location: " +
		// location.toASCIIString());
		// // Expected to be an absolute URI
		// } finally {
		// response.close();
		// }
		CloseableHttpClient httpclient = HttpClients.createDefault();

		HttpPost httpPost = new HttpPost("http://www.baidu.com");
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("username", "vip"));
		nvps.add(new BasicNameValuePair("password", "secret"));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		CloseableHttpResponse response2 = httpclient.execute(httpPost);

		try {
			System.out.println(response2.getStatusLine());
			HttpEntity entity2 = response2.getEntity();
			// do something useful with the response body
			// and ensure it is fully consumed
			EntityUtils.consume(entity2);
		} finally {
			response2.close();
		}

		// LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
		// CloseableHttpClient httpclient = HttpClients.custom()
		// .setRedirectStrategy(redirectStrategy)
		// .build();
	}

	@Test
	public void test2() throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append(
				"<!DOCTYPE html><html><head><meta charset=\"UTF-8\" /><meta http-equiv=\"cache-control\" content=\"no-cache\" /></head><body>");
		sb.append("my test!!");
		sb.append("</body></html>");
		LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
		HttpClientContext context = HttpClientContext.create();
		RequestConfig requestConfig = RequestConfig.custom().setRedirectsEnabled(true).setRelativeRedirectsAllowed(true)
				.build();
		context.setRequestConfig(requestConfig);
//		CloseableHttpClient httpclient = HttpClients.createDefault();
		// CloseableHttpClient httpclient =
		// HttpClients.custom().disableRedirectHandling().build();
		// CloseableHttpClient httpclient =
		// HttpClients.custom().setRedirectStrategy(redirectStrategy).build();
		 CloseableHttpClient httpclient = HttpClientBuilder.create()
		 .setRedirectStrategy(new LaxRedirectStrategy())
		 .build();

		HttpPost httpPost = new HttpPost("http://pdf.starpost.cn");
		// HttpPost httpPost = new HttpPost("http://yinhanglilv.net");

		httpPost.setHeader("User-Agent", "Mozilla");
		httpPost.setHeader("Cache-Control", "no-cache");
		httpPost.setHeader("Pragma", "no-cache");
		httpPost.setHeader("Expires", "0");
		httpPost.setHeader("Cache-Control", "no-store");
		httpPost.setHeader("Cache-Control", "must-revalidate");

		httpPost.setHeader("Page-Width", "100");
		httpPost.setHeader("Page-Height", "100");
		httpPost.setHeader("Margin-Top", "0");
		httpPost.setHeader("Margin-Bottom", "0");
		httpPost.setHeader("Margin-Left", "0");
		httpPost.setHeader("Margin-Right", "0");

		// StringEntity se = new StringEntity(sb.toString(),
		// ContentType.create("text/html", Consts.UTF_8));
		ByteArrayEntity se = new ByteArrayEntity(sb.toString().getBytes(),
				ContentType.create("text/html", Consts.UTF_8));
		httpPost.setEntity(se);

		 CloseableHttpResponse response = httpclient.execute(httpPost,
		 context);
//		CloseableHttpResponse response = httpclient.execute(new HttpGet("http://yinhanglilv.net"));

		HttpHost target = context.getTargetHost();
		// System.out.println("target==" + target.getHostName());
		// System.out.println("httpPost.getURI()==="+httpPost.getURI().toString());
		 System.out.println("context==="+context.getRedirectLocations());

		System.out.println("-------------------------------------------------------");
		try {
			System.out.println(response.getStatusLine());
			HttpEntity entity2 = response.getEntity();
			System.out.println("entity====" + EntityUtils.toString(httpPost.getEntity()));
			System.out.println("entity2==" + entity2);
			System.out.println("response.getHeaders==" + response.getAllHeaders().length);
			for (Header h : response.getAllHeaders()) {
				System.out.println(h.getName() + "===" + h.getValue());
			}

			int status = response.getStatusLine().getStatusCode();
			if (status < 400 && entity2 != null) {
				byte[] resData = EntityUtils.toByteArray(entity2);
				FileUtils.writeByteArrayToFile(new File("target/p.pdf"), resData);
			}
			EntityUtils.consume(entity2);
		} finally {
			response.close();
		}
	}
}
